(ns win.registry
  (:import [com.sun.jna.platform.win32 Advapi32Util WinReg]))

(defn- HKEY [k]
  (case k
    :HKCU WinReg/HKEY_CURRENT_USER
    :HKLM WinReg/HKEY_LOCAL_MACHINE

    :HKEY_CURRENT_USER WinReg/HKEY_CURRENT_USER
    :HKEY_LOCAL_MACHINE WinReg/HKEY_LOCAL_MACHINE

    "HKEY_CURRENT_USER" WinReg/HKEY_CURRENT_USER
    "HKEY_LOCAL_MACHINE" WinReg/HKEY_LOCAL_MACHINE))

(defn registryGetStringValue
  ([root path key]
    (Advapi32Util/registryGetStringValue (HKEY root) path key))
  ([path key]
    (let [[_ k path] (re-matches #"(\w+)\\(.+)" path)]
      (registryGetStringValue k path key))))

(defn registryValueExists
  ([root path key]
    (Advapi32Util/registryValueExists (HKEY root) path key))
  ([path key]
    (let [[_ k path] (re-matches #"(\w+)\\(.+)" path)]
      (registryValueExists k path key))))

(defn global-system-env [k]
  (if (registryValueExists "HKEY_CURRENT_USER\\Environment" k)
    (registryGetStringValue "HKEY_CURRENT_USER\\Environment" k)
    (registryGetStringValue "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment" k)))

